package kevin.workplan.web.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import kevin.workplan.database.gen.model.Plan;
import kevin.workplan.database.gen.model.PlanExample;
import kevin.workplan.database.gen.model.Projects;
import kevin.workplan.service.PlanService;
import kevin.workplan.util.PageUtil;
import kevin.workplan.util.PlanUtil;
import kevin.workplan.util.Util;
import kevin.workplan.web.controller.base.BaseJsonController;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/work/tree")
public class TreePlanController extends BaseJsonController {
	@Autowired
	private PlanService planService;

	@RequestMapping("/list")
	public String list(HttpServletRequest request,
			HttpServletResponse response, HttpSession session) throws Exception  {
		
		return "plan/list";
	}
	
	@RequestMapping("/search.json")
	@ResponseBody
	public Map<String,Object> search(HttpServletRequest request,
			HttpServletResponse response, HttpSession session) throws Exception  {
		long id = PageUtil.getLong(request, "id");
		if(id==0) {
			List<Projects> bp = planService.getChildProjects(1l, 0l);
			for(Projects p : bp) {
				List<Projects> sp = planService.getChildProjects(1l, p.getId());
				p.setChildren(sp);
			}
			Map<String,Object> data = new HashMap<String,Object>();
			data.put("total", 10);
			data.put("rows", bp);
			return successResult(data);
		} else {
			int pagesize = PageUtil.getPagesize(request);
			int curpage = PageUtil.getCurpage(request);
			
			String orderp = request.getParameter("order");
			String sort = request.getParameter("sort");
			String orderby = null;
			if(Util.empty(orderp) || Util.empty(sort)) {
				 sort = "start_time";	// 默认排序
				 orderp = "asc";
			} else {
				sort = Util.underscoreName(sort);
			}
			orderby = sort + " " + orderp;
			request.setAttribute("orderp", orderp);
			request.setAttribute("sort", sort);
			
			PlanExample px = PlanUtil.genPlanExample(request,1L);
			List<Plan> dataList = planService.search(px ,curpage, pagesize, orderby);
			int count = planService.searchCount(px);
			
			Map<String,Object> data = new HashMap<String,Object>();
			data.put("total", count);
			data.put("rows", dataList);
			
			return successResult(data);
		}
		
	}
}
